package com.crlui.component
{
	import com.crlui.control.TabItem;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.EventDispatcher;

	public class TabNavigate extends EventDispatcher
	{
		private var container:DisplayObjectContainer;
		
		private var list:Vector.<TabItem>;
		
		protected var _selectedItem:TabItem;
		public function TabNavigate(container:DisplayObjectContainer)
		{
			this.container=container;
			
			list=new Vector.<TabItem>();
		}
		
		public function add(value:TabItem):Boolean{
			if(list.indexOf(value) !=-1){
				return false;
			}
			list.push(value);
			value.addEventListener(Event.SELECT,selectHandle);
			return true;
		}
		
		public function remove(value:TabItem):Boolean{
			var index:int=list.indexOf(value);
			if(index==-1){
				return false;
			}
			
			list.splice(index,1);
			
			
			if(value==_selectedItem){
				selectedItem=null;
			}else{
				value.removeEventListener(Event.SELECT,selectHandle);
			}
			
			
			return true;
		}
		
		private function selectHandle(event:Event):void{
			var target:TabItem=event.target as TabItem;
			if(target==selectedItem)return;
			if(target.selected){
				selectedItem=target;
			}
		}
		
		public function get selectedItem():TabItem{
			return _selectedItem;
		}
		
		
		public function set selectedIndex(value:int):void{
			if(value<0){
				selectedItem=null;
			}
			if(value>=list.length){
				value=list.length-1;
			}
			
			selectedItem=list[value];
		}
		
		public function get selectedIndex():int{
			if(_selectedItem==null){
				return -1;
			}
			return list.indexOf(_selectedItem);
		}
		
		public function set selectedItem(value:TabItem):void{
			var target:DisplayObject;
			
			if(_selectedItem){
				_selectedItem.selected=false;
				_selectedItem.enabled=true;
				_selectedItem.addEventListener(Event.SELECT,selectHandle);
				target=_selectedItem.target;
				if(target)container.removeChild(target);
			}
			_selectedItem=value;
			
			if(_selectedItem){
				_selectedItem.removeEventListener(Event.SELECT,selectHandle);
				_selectedItem.selected=true;
				_selectedItem.enabled=false;
				target=_selectedItem.target;
				if(target)container.addChild(target);
			}
			
			this.dispatchEvent(new Event(Event.CHANGE));
		}
	}
}